import config from "./config";
import { getAccessToken, removeToken, removeUserInfo } from "./auth";
import { toast, showConfirm, tansParams } from "./common";
import Taro from "@tarojs/taro";

const errorCode = {
  401: "认证失败，无法访问系统资源",
  403: "当前操作没有权限",
  404: "访问资源不存在",
  default: "系统未知错误，请反馈给管理员",
};

let timeout = 3000;
const baseUrl = config.baseUrl;
const HOST = config.HOST;

const request = (config) => {
  let token = getAccessToken();
  if (token != "") {
    config.header = {
      ...config.header,
      "Authorization":'Bearer '+ token,
    };
  }
  return new Promise((resolve, reject) => {
    if (!config.noLoad) {
      //不要loading
      Taro.showLoading({
        title: "加载中",
      });
    }
    Taro.request({
      method: config.method || "get",
      timeout: config.timeout || timeout,
      url: baseUrl + HOST + config.url,
      data: config.body,
      header: config.header,
      dataType: "json",
    })
      .then((res) => {
        Taro.hideLoading();
        const code = res.data.code || 200;
        const msg = errorCode[code] || res.data.message || errorCode["default"];
        if (code === 401) {
          removeUserInfo();
          removeToken();
          showConfirm(
            "登录状态已过期，您可以继续留在该页面，或者重新登录?"
          ).then((res) => {
            if (res.confirm) {
              Taro.reLaunch({
                url: "/pages/login/index",
              });
            }
          });
          // reject("无效的会话，或者会话已过期，请重新登录。");
        } else if (code === 500) {
          toast(msg);
        } else if (code !== 200) {
          toast(msg);
        }
        resolve(res);
      })
      .catch((error) => {
        toast(error.errMsg);
        reject(error.message);
      });
  });
};

export default request;

export function uploadFile(tempFilePaths, type) {
  return new Promise((resolve, reject) => {
    Taro.uploadFile({
      url:
        baseUrl +
        HOST +
        "/app/file/upload?type=" +
        type +
        "&path=" +
        tempFilePaths,
      filePath: tempFilePaths,
      name: "file",
      header: {
        "X-Access-Token": getAccessToken(),
      },
      success(res) {
        resolve(res.data);
      },
      fail(err) {
        reject(err);
      },
    });
  });
}
